﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace CoolCode.Controls
{
    public interface IClosableHeader
    {
        System.Windows.Visibility ButtonIsVisibility { get; set; }
        string HeaderText { get; set; }
    }

    public class XTabItem : TabItem
    {
        public XTabItem()
            : base()
        {
            this.DefaultStyleKey = typeof(TabItem);

        }

        protected override void OnHeaderChanged(object oldHeader, object newHeader)
        {
            if (oldHeader != null)
            {
                Type otype = oldHeader.GetType();
                if (newHeader == null) return;
                Type ntype = newHeader.GetType();
                if (ntype == typeof(string))
                {
                    Header = new XHeader() { HeaderText = newHeader.ToString() };
                }
                else if (ntype == typeof(XHeader))
                {
                    // OnApplyTemplate();
                }
            }
            else
            {
                if (newHeader == null) return;
                Type ntype = newHeader.GetType();
                if (ntype == typeof(string))
                {
                    Header = new XHeader() { HeaderText = newHeader.ToString() };
                }
                else if (ntype == typeof(XHeader))
                {
                    //   OnApplyTemplate();
                }
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            var h = Header as XHeader;
            if (h != null)
            {
                //if (h.close.Click == null)
                //{
                if (this.OnClose != null)
                    h.close.Click += this.OnClose;
                h.close.Click += new RoutedEventHandler(close_Click);
                //}
                //ButtonBase close = h.FindName("close") as ButtonBase;// this.GetTemplateChild
                //if (close != null)
                //    close.Click += new RoutedEventHandler(close_Click);
            }
        }

        void close_Click(object sender, RoutedEventArgs e)
        {
            var parent = this.Parent as TabControl;
            if (parent != null)
            {
                //if (this.OnClose != null)
                //    OnClose(sender, e);
                parent.Items.Remove(this);
            }
        }

        public RoutedEventHandler OnClose { get; set; }
    }
}
